//
// Created by 11510 on 2025/10/2.
//

#include "PingCommand.h"
#include "RegistryContainer.hpp"
#include "CameraApp.h"

xclib_client::PingCommand::PingCommand(CommandContext ctx) : ICommand("ping", ctx) {}

std::optional<std::future<int>> xclib_client::PingCommand::run(const std::vector<std::string> &args, bool wait) {
    cxxopts::Options options("ping", "ping command");
    options.add_options()
            ("u,unit", "unit", cxxopts::value<uint16_t>()->default_value(""))
            ("help", "print help");
    try {
        auto result = parseOptions(options, args);
        if (result.count("help")) {
            std::cout << options.help() << '\n';
            return std::nullopt;
        }
        auto u = result["unit"].as<uint16_t>();
        auto task = [u]() {
            std::cout << "Pinging unit='" << u << "'...\n";
            registry::RegistryContainer::instance().get<CameraApp>("lazy")->ping(u);
            std::this_thread::sleep_for(std::chrono::milliseconds(300));
            std::cout << "pong\n";
            return 0;
        };
        if (!wait) {
            return make_optional(async(std::launch::async, task));
        } else {
            task();
            return std::nullopt;
        }
    } catch (const cxxopts::exceptions::exception &e) {
        std::cerr << "ping: option parse error: " << e.what() << '\n';
        return std::nullopt;
    }
}

std::string xclib_client::PingCommand::shortHelp() const { return "ping -u <unit>"; }

std::string xclib_client::PingCommand::longHelp() const { return "ping -u <unit>\n    send ping to unit"; }